# -*- coding: utf-8 -*-

import sys,json,os,subprocess,uuid,re,traceback,logging
from .. import config as C
from . import fs
from . import py
from fontTools import subset

#PROTOC命令目录
if sys.platform == 'win32':
	CMD_PROTOC = os.path.join(C.BASE_PATH, 'libs', 'protoc', 'bin', 'protoc.exe')
	if not os.path.exists(CMD_PROTOC):
		logging.error('not found %s !!!', CMD_PROTOC)

def getConfig():
	'''
		获得配置对象
	'''
	return py.readJson(C.CONFIG_FILE)
	
def fullConfigPath(*path):
	'''
		补全配置的路径
	'''
	return os.path.join(C.BASE_PATH, *path)

def fontSubset(fromFont, toFont, *textlist):
	'''
		字体裁剪
		@param textlist 文本字符串数组
	'''
	options = subset.Options()
	font = subset.load_font(fromFont, options)
	subsetter = subset.Subsetter(options)
	subsetter.populate(text="".join(textlist))
	subsetter.subset(font)
	subset.save_font(font, toFont, options)

def protoJS(protoFile):
	'''
		编辑proto为js
	'''
	protoDir = os.path.dirname(protoFile)
	subprocess.call([
		CMD_PROTOC,
		'--js_out=import_style=commonjs,binary:' + protoDir,
		'-I', protoDir,
		protoFile
	])

def getVersionName(vercode):
	'''
		通过版本号获得版本名
	'''
	verps = []
	while True:
		verps.insert(0,vercode % 1000)
		if vercode < 1000:
			break
		else:
			vercode /= 1000
	vername = ""
	for ver in verps:
		if len(vername) > 0:
			vername += "."
		vername += "%d" % ver
	return vername
	
def getVersionCode(vername):
	'''
		通过版本名获得版本号
	'''
	vercode = 0
	verss = vername.split(".")
	for ver in verss:
		vercode *= 1000
		vercode += int(ver)
	return vercode
	
def getClientPackPath(sPath, packName):
	'''
		获得客户端包路径
	'''
	if os.path.isdir(sPath):
		for f in os.listdir(sPath):
			fPath = os.path.join(sPath, f)
			if not fPath.endswith(".meta"):
				mFile = fPath + ".meta"
				if os.path.isdir(fPath) and os.path.isfile(mFile):
					metaConf = py.readJson(mFile)
					isBundle = py.getDictPath(metaConf, "userData.isBundle", False)
					bundleName = py.getDictPath(metaConf, "userData.bundleName", "")
					if len(bundleName) <= 0:
						bundleName = f
					if isBundle and bundleName == packName:
						return fPath
				pPath = getClientPackPath(fPath, packName)
				if pPath != None:
					return pPath
		